package org.zb.object;

import org.newdawn.slick.Animation;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.SpriteSheet;
import org.newdawn.slick.geom.Vector2f;
import org.zb.controller.GameController;
import org.zb.resource.ImagesManager;

public class Enemy extends SmartMovingObject {

	Animation[] animations; 
	
	@Override
	public void init() {
		speed = 0.3f;
		
		SpriteSheet sheet = ImagesManager.instance.getSpriteSheet(this);
		animations = new Animation[sheet.getVerticalCount()];
		
		for(int i=0;i<animations.length;i++) {
			animations[i] = new Animation(sheet, 0, i, sheet.getHorizontalCount() - 1, i, true, (int)(8/speed), false);
		}
	}
	
	@Override
	public void render(GameContainer gc, Graphics g, int offsetX, int offsetY) throws SlickException {
		calculateAnimation().draw(position.x - 25 + offsetX, position.y - 90 + offsetY);
	}

	@Override
	public void update(GameContainer container, int delta) throws SlickException {
		Vector2f playerPos = GameController.objectController.player.position;
		
		if(Math.random() < 0.1) {
			double rnd = position.distance(playerPos) / 2;
			target.set(playerPos);
			
			target.x += (Math.random() * rnd / 2) - rnd;
			target.y += (Math.random() * rnd / 2) - rnd;
		}
		
		super.update(container, delta);

		if(hasMoved)
			for(Animation a: animations)
				a.update(delta);
	}
	
	private final Animation calculateAnimation() {
		double theta = calculateTheta();
		int frame = ((int)Math.round(32 * -theta / 360) + 40) % 32;
		//Log.debug(" theta = " + theta + ", frame = " + frame);
		return animations[frame];
	}
}
